import Switch from '@/components/switch'
import { ADMIN_ID, PARTNER_ID } from '@/constant'
import { updateUserRight } from '@/api/admin'
import Toast from '@/components/toast'

const updateRight = async (type, data, user, isAdmin, updateAppleNumbers) => {
  const res = await updateUserRight({ status: type ? 1 : 2, ...data })

  if (res.code === 0) {
    updateAppleNumbers()
    if (user.email === data.email) {
      Toast.normal('您正在修改当前账号权限，即将为您刷新页面')
      setTimeout(() => {
        if (isAdmin) {
          window.location.replace('/market-center')
        } else {
          window.location.reload()
        }
      }, 1000)
    } else {
      Toast.normal('操作成功')
    }
  }
}

const columns = (user, updateAppleNumbers) => {
  const cols = [
    {
      left: 40,
      title: '用户ID',
      dataIndex: 'id',
      width: '17%',
      headerAlign: 'left',
      bodyAlign: 'left',
    },
    {
      title: '账号邮箱',
      dataIndex: 'email',
      width: '16%',
    },
    {
      title: '管理员',
      dataIndex: 'amount',
      width: '16%',
      render: (row) => {
        const admin = row.actors.find((item) => item.actorType === ADMIN_ID)
        return (
          <Switch
            defaultChecked={admin?.status === 1}
            onChange={(isOpen) =>
              updateRight(
                isOpen,
                { userId: row.id, actorId: admin.actorId, email: row.email },
                user,
                true,
                updateAppleNumbers
              )
            }
          />
        )
      },
    },
    {
      title: '联盟伙伴',
      dataIndex: 'amount',
      width: '16%',
      render: (row) => {
        const partner = row.actors.find((item) => item.actorType === PARTNER_ID)
        return (
          <Switch
            defaultChecked={partner?.status === 1}
            onChange={(isOpen) =>
              updateRight(
                isOpen,
                { userId: row.id, actorId: partner.actorId, email: row.email },
                user,
                false,
                updateAppleNumbers
              )
            }
          />
        )
      },
    },
  ]
  return cols
}

export default columns
